package com.example.myapplication;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;

import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.Base64;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Photo_Sumbit_Activity extends AppCompatActivity {
    ImageView imageViewFront,imageViewBack;
    String front_name,back_name;
    Map<String,String> imageMap=new HashMap<>();
    Button button;
    Map<Object,Object> bodyFront=new HashMap<>();
    Map<Object,Object> bodyBack=new HashMap<>();
    ExecutorService executor = Executors.newSingleThreadExecutor();
    String response1,response2;
    TextView textView;
    Context context;
    Bitmap bitmap;
    @SuppressLint("MissingInflatedId")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        bodyInit();

        setContentView(R.layout.activity_photo_sumbit);
        imageViewFront=findViewById(R.id.image_front);
        imageViewFront.setImageResource(R.drawable.front);
        imageViewBack=findViewById(R.id.image_back);
        imageViewBack.setImageResource(R.drawable.back);
        button=findViewById(R.id.button2);
        textView=findViewById(R.id.textView);
        context=this;
        Activity activity=this;
        imageViewFront.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (ContextCompat.checkSelfPermission(context,
                        "android.permission.CAMERA")
                        != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(activity,
                            new String[]{"android.permission.CAMERA"},
                            1);
                } else {
                    String name="Front";
                    // 权限已经被授予，可以打开相机
                    openCamera(name);
                }
            }
        });

        imageViewBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (ContextCompat.checkSelfPermission(context,
                        "android.permission.CAMERA")
                        != PackageManager.PERMISSION_GRANTED) {
                    ActivityCompat.requestPermissions(activity,
                            new String[]{"android.permission.CAMERA"},
                            1);
                } else {
                    String name="Back";
                    // 权限已经被授予，可以打开相机
                    openCamera(name);
                }
            }
        });

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                try {
                    bodyBuild();
                } catch (IOException e) {
                    throw new RuntimeException(e);
                } catch (NoSuchAlgorithmException e) {
                    throw new RuntimeException(e);
                } catch (InvalidKeyException e) {
                    throw new RuntimeException(e);
                }
            }
        });

    }

    private void openCamera(String name) {
        Intent intent=new Intent(this,CameraActivity.class);
        intent.putExtra("name",name);
        startActivityForResult(intent,1);
    }

    private void bodyInit() {
        bodyFront.put("Config", "{\"TempIdWarn\":true}");
        bodyBack.put("Config", "{\"TempIdWarn\":true}");
    }

    private void bodyBuild() throws IOException, NoSuchAlgorithmException, InvalidKeyException {
        String frontName = imageMap.get("Front");
        String imageBaseFront = getimageBase64(frontName);

        bodyFront.put("ImageBase64",imageBaseFront);
        bodyFront.put("CardSide","FRONT");

        String backName = imageMap.get("Back");
        String imageBaseBack = getimageBase64(backName);
        bodyBack.put("ImageBase64",imageBaseBack);
        bodyBack.put("CardSide","BACK");

        Gson gson = new Gson();
        String bodyFrontJson = gson.toJson(bodyFront);
        String bodyBackJson = gson.toJson(bodyBack);

        executor.execute(new Runnable() {
            @Override
            public void run() {
                // 在这里执行网络操作
                // 例如使用HttpURLConnection或者HttpClient
                try {
                    response1 = TencentHttpUtil.doRequest(bodyFrontJson);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                } catch (NoSuchAlgorithmException e) {
                    throw new RuntimeException(e);
                } catch (InvalidKeyException e) {
                    throw new RuntimeException(e);
                }
                try {
                    response2 = TencentHttpUtil.doRequest(bodyBackJson);
                } catch (IOException e) {
                    throw new RuntimeException(e);
                } catch (NoSuchAlgorithmException e) {
                    throw new RuntimeException(e);
                } catch (InvalidKeyException e) {
                    throw new RuntimeException(e);
                }
                // 当网络操作完成后，切换到主线程更新UI
                runOnUiThread(new Runnable() {
                    @SuppressLint("SetTextI18n")
                    @Override
                    public void run() {
                        Log.d("zyy","response:"+response1);
                        Log.d("zyy","response"+response2);

                        if(hasErrorKey(response1) || hasErrorKey(response2)){
                            if(hasErrorKey(response1)){
                                Log.d("zyy","错误1");
                                textView.setText("上传错误！具体错误信息："+getErrorFromResponse(response1));
                            }

                            if(hasErrorKey(response2)){
                                Log.d("zyy","错误2");
                                textView.setText("上传错误！具体错误信息："+getErrorFromResponse(response2));
                            }
                            // 这里写上刷新页面的代码，例如重新发起网络请求
                            new Handler().postDelayed(Photo_Sumbit_Activity.this::refreshPage, 20000);
                        }
                        else{
                            Intent intent=new Intent(context,MsgDetailActivityFront.class);
                            intent.putExtra("responseFront",response1);
                            intent.putExtra("responseBack",response2);

                            String frontName = imageMap.get("Front");
                            Bitmap bitmapTemp=getImage(frontName);
                            intent.putExtra("imageFront",bitmapTemp);

                            String backName = imageMap.get("Back");
                            bitmapTemp=getImage(backName);
                            intent.putExtra("imageBack",bitmapTemp);

                            startActivity(intent);
                        }
                    }
                });
            }
        });
    }

    private String getimageBase64(String frontName) {
        File file=new File("/data/data/com.example.myapplication/"+frontName);
        try (InputStream is = new FileInputStream(file)) {
            byte[] buffer = new byte[(int) file.length()];
            is.read(buffer);
            Log.d("zyy","buffer"+Base64.getEncoder().encodeToString(buffer) );
            return Base64.getEncoder().encodeToString(buffer);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    private Bitmap getImage(String frontName){
        File file=new File("/data/data/com.example.myapplication/"+frontName);

        try (InputStream is = new FileInputStream(file)) {
            byte[] buffer = new byte[(int) file.length()];
            is.read(buffer);
            bitmap = BitmapFactory.decodeByteArray(buffer, 0, buffer.length);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
        return bitmap;
    }

    public static boolean hasErrorKey(String jsonString) {
        try {
            JSONObject jsonObject = new JSONObject(jsonString);
            JSONObject response = jsonObject.getJSONObject("Response");
            JSONObject error = response.getJSONObject("Error");

            String errorCode = error.getString("Code");
            String errorMessage = error.getString("Message");

            if(!errorMessage.isEmpty()){
                Log.d("zyy",errorMessage);
                return true;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return false;
    }

    private void refreshPage(){
        textView.setText("");
        imageViewFront.setImageResource(R.drawable.front);
        imageViewBack.setImageResource(R.drawable.back);
    }

    private String getErrorFromResponse(String jsonString) {
        try {
            JSONObject jsonObject = new JSONObject(jsonString);
            JSONObject response = jsonObject.getJSONObject("Response");
            JSONObject error = response.getJSONObject("Error");

            String errorCode = error.getString("Code");
            String errorMessage = error.getString("Message");

            HashMap<String, Object> hashMap = new HashMap<>();
            response.keys().forEachRemaining(key -> {
                try {
                    hashMap.put(key, response.get(key));
                } catch (JSONException e) {
                    throw new RuntimeException(e);
                }
            });
            Log.d("zyy","MAP"+hashMap);
//            StringBuilder stringBuilder=new StringBuilder();
//            for (String key : hashMap.keySet()) {
//                Object value = hashMap.get(key);
//                stringBuilder.append(key).append(": ").append(value.toString()).append("\n"); // 添加键值对到StringBuilder，并换行
//            }
//            textView.setText(stringBuilder);
            return errorMessage;

        } catch (Exception e) {
            e.printStackTrace();
        }
        return "";
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        Log.d("zyy","two");
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1 && resultCode == RESULT_OK) {
            Bundle extras = data.getExtras();
            assert extras != null;
            String name= (String) extras.get("name");
            Bitmap bitmap = (Bitmap) extras.get("image");
            String image= (String) extras.get("imageName");
            if(name.equals("Front")){
                imageMap.put("Front",image);
                imageViewFront.setImageBitmap(bitmap);
            }
            else{
                imageMap.put("Back",image);
                imageViewBack.setImageBitmap(bitmap);
            }

        }
    }



}